<template>
<!-- 采购入库页面 -->
  <div >



<div style="display: flex;  align-items: center;  height: 45px; background-color: white;">
  <el-input placeholder="请输入药品名" style="width: 20%;" @input="handlePurchaseKeyChange" v-model="purchaseKey" >
    <template slot="prepend">药品名：</template>
  </el-input>
 
 

  <div style="display: flex; justify-content: flex-end; flex: 1;" >
    <el-button type="primary"   @click="handleAdd" style="margin-right: 10px;">添加药品</el-button>

    <el-tooltip class="tooltip" effect="dark" content="未勾选药品" placement="top" :disabled="!multiple">
  <div >
      <el-button type="primary"   :disabled="multiple" @click="open1=true " > 批量设置</el-button>
</div>
    </el-tooltip>



   
 
<el-tooltip class="tooltip" effect="dark" :content="content" placement="top" :disabled="!a">
  <div >
       <el-button type="primary"  :disabled="a" @click="submitPurchaseList">审核入库</el-button>
       </div>
    </el-tooltip>
<el-tooltip class="tooltip" effect="dark" :content="content" placement="top" :disabled="!a">
  <div >
    <el-button type="primary"   :disabled="a" @click="submitPurchaseListDirectly">直接入库</el-button>
    </div>
    </el-tooltip>
  </div>
</div>

<br>



<div class="my-custom-container">
  <div>
    <span>采购号：</span>
    <span>{{ batchesOfInventoryNumber }}</span>
    &nbsp; &nbsp;
      <span>采购员：</span>
        <span>{{ getCookieValue("username") }}</span>
  </div>
  

  
  <div style="margin-right: 30px;">
    <span>供应商选择：</span>
    <el-select placeholder="请选择" class=""  v-model="supplierId">
      <el-option
        v-for="item in supplierList"
        :key="item.sid"
        :label="item.supplierName"
        :value="item.sid">
      </el-option>
    </el-select>
  </div>
  <!-- &nbsp; &nbsp;
  
  <span>当前日期：{{ currentTime }}</span> -->
</div>
<div class="sidebar">
   批发总金额：<span style="color:red;">{{purchaseTradePriceTotle}}</span>
  &nbsp;&nbsp;
  处方总金额：<span style="color:red;">{{purchasePrescriptionPriceTotle}}</span>
   &nbsp;&nbsp;
  
  

   
      <el-button type="danger"   @click="delInfo">清空数值</el-button>


</div>
  <el-table :data="paginatedPurchaseList" @selection-change="handleSelectionChange" ref="table">
      <el-table-column type="selection" width="55"   align="center" />
 
      <el-table-column label="药品名称：" align="center" prop="medicinesName" />
  
      
      <el-table-column label="采购数量" align="center"  >
      <template slot-scope="scope">
         <el-input-number v-model="scope.row.purchaseNum" controls-position="right"  :min="0" :aria-required="true"></el-input-number>
      
    </template>
    </el-table-column>
      <el-table-column label="批发价" align="center"  >
      <template slot-scope="scope">
          <el-input-number v-model="scope.row.purchaseTradePrice" :precision="2" :step="0.1" :min="0.00"  ></el-input-number>
    
    </template>
    </el-table-column>
      <el-table-column label="处方价" align="center"  >
      <template slot-scope="scope">
      <el-input-number v-model="scope.row.purchasePrescriptionPrice" :precision="2" :step="0.1" :min="0.00"  />

      
    </template>
    </el-table-column>
      <el-table-column label="采购批发总额" align="center"  >
         
      <template slot-scope="scope">
        {{ scope.row.purchaseTradePrice * scope.row.purchaseNum }}
      </template>
    </el-table-column>
      <el-table-column label="采购处方总额" align="center"  >
        
      <template slot-scope="scope">
        {{ scope.row.purchasePrescriptionPrice * scope.row.purchaseNum }}
      </template>
    </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          
         
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index)"
         
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
     
    <el-pagination :page-sizes="[5, 10, 15]" :page-size="pageSize" :total="purchaseList.length" :current-page="currentPage"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper"></el-pagination>




    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>


<div class="form-container">
  <span class="label">药品名：</span>
  <el-input placeholder="请输入内容" v-model="queryParams.medicinesName" class="form-item" style="width: 200px"></el-input>
  <span class="label">药品分类：</span>
  <el-select placeholder="请选择" class="form-item" v-model="queryParams.medicinesClass" style="width: 150px">
    <el-option
      v-for="(item,index) in medicinesClasses"
      :key="index"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
  <el-button type="primary" @click="getMedicinesList" class="form-item">搜索</el-button>
   <el-button type="primary" @click="reset" class="form-item">重置</el-button>
</div>

  <el-table :data="tableData" @selection-change="handleSelectionChange1" ref="table1">
    <el-table-column type="selection" width="55" align="center" :selectable="isHaven" />
    <el-table-column label="药品编号" prop="medicinesNumber" align="center" />
    <el-table-column label="药品名称" align="center" prop="medicinesName" />
    <el-table-column label="药品分类" align="center" prop="medicinesClass" />
     <el-table-column label="创建日期" align="center"  >
       <template slot-scope="scope">
    {{ formatDate(scope.row.createTime, scope.row) }}
  </template>   
       
     </el-table-column>
  </el-table>



   <el-pagination :page-sizes="[5, 10, 15]" :page-size="queryParams.pageSize" :total="total" :current-page="queryParams.pageNum"
      @size-change="handleSizeChange1" @current-change="handleCurrentChange1" layout="total, sizes, prev, pager, next, jumper"></el-pagination>





  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="submitForm" :disabled="ids1.length == 0" class="add-button">添加</el-button>
    <el-button @click="cancel">取消</el-button>
  </div>
</el-dialog>


  <!-- 药品修改弹窗 -->
<el-dialog
  :title="title"
  :visible.sync="open1"
  width="30%"
>
  <div class="dialog-content">
    <el-input placeholder="请输入药品数" class="dialog-input" v-model="purchaseNum" oninput="value=value.replace(/[^\d.]/g,'')" >
      <template slot="prepend">药品数量：</template>
    </el-input>  
    <el-input placeholder="请输入批发价" class="dialog-input" v-model="purchaseTradePrice" oninput="value=value.replace(/[^\d.]/g,'')">
      <template slot="prepend">批发价：</template>
    </el-input>
    
    <el-input placeholder="请输入处方价" v-model="setPurchasePrescriptionPrice" class="dialog-input"  oninput="value=value.replace(/[^\d.]/g,'')">
      <template slot="prepend">处方价：</template>
      <el-select v-model="prescriptionPriceType" slot="append" placeholder="请选择" style="width:200px" >
        <el-option 
          v-for="(item,index) in prescriptionPriceTypeList"
      :key="index"
      :label="item.label"
      :value="item.value">
        </el-option>
      
      </el-select>
    </el-input>
  </div>

  <span slot="footer" class="dialog-footer ">
    <el-button type="primary" @click="handleUpdate" class="dialog-input">应用</el-button>
  </span>
</el-dialog>



  </div>
</template>
<script>
  import  dayjs  from 'dayjs';
  import {getMedicines,getSuppliers,insertMedicines} from '@/api/medicines.js'
import { computed } from 'vue';
 
      
export default {

  name: "Cgrk",
  data() {
    return {

         

            purchaseNum: '',//采购数量
            purchaseTradePrice: '',//批发价
            purchasePrescriptionPrice: '',//处方价
               setPurchasePrescriptionPrice: '',//计算处方价
      
      purchaseList: [],//采购列表
           
      
    
    currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示条数
      total: 0, // 数据总条数
      tableData: [], // 弹出框表格数据

       prescriptionPriceType: 1,// 处方价设定方式
      supplierId: null, // 供应商选择
     
   
      //采购单编号
      batchesOfInventoryNumber: 0,
  
      
       purchaseKey: '',//采购药品搜索字
      
      // 供货商信息
      supplierList: [], 
      // 弹出层标题
      title: "",
      // 添加按钮是否显示弹出层
      open: false,
       // 批量设置，修改是否显示弹出层
      open1: false,
      // 弹窗选中药品数组
      ids1: [],
       // 选中数组
      ids: [],
       // 非多个禁用
      multiple: true,
       
      //获取当前时间
       currentTime: '',
    //药品分类
       medicinesClasses:
        [{
            value: '中草药',
            label: '中草药'
          }, {
            value: '西药',
            label: '西药'
          }]
        ,

         //处方价设定方式
       prescriptionPriceTypeList:
        [{
            value: 1,
            label: '批发价+（金额）'
          }, {
            value: 2,
            label: '批发价*（%比例）'
          }]
        ,
         // 查询参数
      queryParams: {
         
        medicinesName: null,
        medicinesClass: null,
        pageSize:5,
        pageNum:1
      },
    };
  },
  created(){
     this.getSupplierList();
       
       this.getMedicinesList();
       
  },
  methods: {
//采购药品页面模糊查询
    handlePurchaseKeyChange(){
    
     

  const regex = new RegExp(this.purchaseKey, 'i');
  const filteredObjects = this.purchaseList.filter(obj => regex.test(obj.medicinesName));
  this.purchaseList = [...filteredObjects, ...this.purchaseList.filter(obj => !regex.test(obj.medicinesName))];
      
    },




    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
//添加药品弹出框分页方法
          // //分页/
      // 每页显示多少条
      handleSizeChange1(val) {
        // 改变每页显示的条数 
        this.queryParams.pageSize=val
        // 注意：在改变每页显示的条数时，要将页码显示到第一页
        this.queryParams.pageNum=1
        this.getMedicinesList();
      
      },
      // 现在显示当前页的第几页
      handleCurrentChange1(val) {
        // 改变默认的页数
        this.queryParams.pageNum=val,
        this.getMedicinesList();
       
      },


    
    reset(){
      this.queryParams.medicinesClass='';
      this.queryParams.medicinesName='';
      this.queryParams.pageNum=1;
      this.pageSize=5;
      this.getMedicinesList();
    },

   

      /** 查询供应商信息列表 */
          getSupplierList() {
      getSuppliers().then(response => {
          
        this.supplierList = response;
      
      });
          },
     /** 查询药品信息列 */
    getMedicinesList() {
      
      getMedicines(this.queryParams).then(response => {
          // this.tableData=response.data.filter(item1 => !this.purchaseList.some(item2 => item2.medicinesId === item1.medicinesId));
    // this.total=response
       this.tableData=response.data.list;
       this.total=response.data.total;
  
        
      
      });
    },
    //获取登录人姓名
    getCookieValue(cookieName) {
  var cookieString = document.cookie;
  var cookies = cookieString.split("; ");
  
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].split("=");
    if (cookie[0] === cookieName) {
      return decodeURIComponent(cookie[1]);
    }
  }
  
  return null;
},

   
     /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      this.open = true;
      this.title = "添加药品";
    },
     // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
        // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item)
      
      this.multiple = !selection.length
    },
          // 弹出框选中数据
    handleSelectionChange1(selection) {
      this.ids1 = selection.map(item => item)
     
      // this.multiple = !selection.length
    },
     //弹窗添加药品按钮
  submitForm(){
    const a=Math.floor(Date.now() / 1000);
const addList=this.ids1.map(item => {
  return {


            medicinesName:item.medicinesName,
            medicinesId: item.medicinesId,//药品信息
            purchaseUnit: item.unit,
            purchaseNum: 0,//采购数量
            purchaseTradePrice: 0.00,//批发价
            purchasePrescriptionPrice: 0.00,//处方价
            hmrId: item.hmrId,
            createTime: a,
           
          
        
    
  };
});
    this.purchaseList.push(...addList);

  //  this.tableData=this.tableData.filter(item1 => !this.purchaseList.some(item2 => item2.medicinesId === item1.medicinesId));
   
     this.open = false;
    //  this.currentPage=1
     this.$refs.table1.clearSelection();

  },
   formatDate(row){
      return dayjs(row).format('YYYY-MM-DD HH:mm:ss')
},
 /** 批量修改，修改按钮操作 */
    handleUpdate() {
   
      this.title = "修改药品信息";
      const a=this.ids;
      if(this.setPurchasePrescriptionPrice!=''&this.purchaseTradePrice==''){
             this.$message({
          message: '批量设置处方价需先设置批发价',
          type: 'warning'
        });
        return;
      }
      
          for (let i = 0; i < a.length; i++) {
      if(this.purchaseNum!=''){ 

  a[i].purchaseNum = this.purchaseNum;
      }
        if(this.purchaseTradePrice!=''){ 

  a[i].purchaseTradePrice = this.purchaseTradePrice;
      }
      if(this.setPurchasePrescriptionPrice!=''){

      
        if(this.prescriptionPriceType==1){
  a[i].purchasePrescriptionPrice = parseFloat(this.setPurchasePrescriptionPrice)+parseFloat(this.purchaseTradePrice);

        }else{
  a[i].purchasePrescriptionPrice = (parseFloat(this.setPurchasePrescriptionPrice)/100+1)*parseFloat(this.purchaseTradePrice);

        }

      }

          }
 this.purchaseNum='';
      this.purchaseTradePrice='';
      this.setPurchasePrescriptionPrice='';
    this.$refs.table.clearSelection();
        
       this.open1 = false; 
       
       
        
      
    },
    // 设置采购单号
    setBatchesOfInventoryNumber(){
    this.batchesOfInventoryNumber=Date.now();
     
    },
// 删除采购药品
    handleDelete(index){
    
      this.purchaseList.splice(index,1);
    
    },
//清空数值
    delInfo(){
       const a=this.purchaseList;
        for (let i = 0; i < a.length; i++) {
  a[i].purchaseNum =0;
  a[i].purchaseTradePrice = 0.00;
  a[i].purchasePrescriptionPrice = 0.00;
}
 
 
    },
     //判断添加药品弹窗所选狂是否可选
    isHaven(row,index){
   
  return !(this.purchaseList.some(item => item.medicinesId === row.medicinesId));

    },
    //直接入库
    submitPurchaseListDirectly(){

      if(this.purchaseIsNull){
          this.$message({
          message: '请完善药品信息，处方价，批发价，采购数量',
          type: 'warning'
        });
      }else{
        
         insertMedicines(this.purchaseList,2,this.batchesOfInventoryNumber,this.supplierId,this.purchaseTradePriceTotle,this.currentTime).then(response => {
      
         this.$message({
          message: '采购入库成功',
          type: 'true'
        });
        this.purchaseList=[];
        this.getMedicinesList();
       
              this.setBatchesOfInventoryNumber();

      
      });

      }
    },
    //审核入库
    submitPurchaseList(){
       if(this.purchaseIsNull){
          this.$message({
          message: '请完善药品信息，处方价，批发价和采购数量都不能为零',
          type: 'warning'
        });
      }else{

         

    

         insertMedicines(this.ids,1,this.batchesOfInventoryNumber,this.supplierId,this.purchaseTradePriceTotle,this.currentTime).then(response => {
          
        this.$message({
          message: '采购成功，请至审核入库页面完成入库操作',
          type: 'true'
        });
               this.purchaseList=[]
              this.getMedicinesList();
              this.setBatchesOfInventoryNumber();
      
      });

      }

    }
  
   
  },


  mounted(){
// 获取当前时间戳
  this.setBatchesOfInventoryNumber();
 
    this.currentTime=dayjs().format('YYYYMMDD');

  },


  computed:{

    supplierIsNull(){
return this.supplierId==null?true:false;
    },

//判断是否有采购药品
    purchaseListIsNull(){
  return this.purchaseList.length==0?true:false;
    
    },
   
//判断采购药品信息是否完善
    purchaseIsNull(){
       const a = this.purchaseList;
     for (let i = 0; i < a.length; i++) {
      let b=a[i];
    if(b.purchasePrescriptionPrice==0 || b.purchaseTradePrice==0 || b.purchaseNum==0){
      return true
    
    }
    
}

return false;
    },
     // 弹出框计算分页后的数据
    // paginatedTableData() {
    //   const start = (this.currentPage - 1) * this.pageSize;
    //   const end = start + this.pageSize;
    //   return this.tableData.slice(start, end);
    // },
      // 采购表格计算分页后的数据
    paginatedPurchaseList() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.purchaseList.slice(start, end);
    },
    //入库按钮提示是否隐藏
a(){
  if(this.supplierIsNull==true || this.purchaseListIsNull==true){
    return true
  }else{
    return false
  } 
},
  //入库按钮是否可以点击
// a(){
//   if(this.supplierIsNull==true || this.purchaseListIsNull==true){
//     return true
//   }else{
//     return false
//   } 
// },

//入库按钮信息提示

    content(){
      if(this.purchaseListIsNull==true){
          return "未添加采购药品"
      }else {
       
          return "未选择供货商"
      }
         
    },
    //全部批发价
      purchaseTradePriceTotle(){
             const a = this.purchaseList;
             let b=0;
     for (let i = 0; i < a.length; i++) {
      let c=a[i]
      b=b+c.purchaseTradePrice*c.purchaseNum;
    

      }
      return b

      },

//全部处方价
            purchasePrescriptionPriceTotle(){
        let a = this.purchaseList;
             let b=0;
     for (let i = 0; i < a.length; i++) {
      let c=a[i]
      b=b+c.purchasePrescriptionPrice*c.purchaseNum;
    

      }
      return b

            },
  


   
}
 
}

  
  


</script>




<style scoped>
.sidebar {
    float: right;
    margin-right: 20px;
    padding: 20px;
  }
.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.dialog-input {
  width: 100%;
}
.form-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
}

.label {
  margin-right: 8px;
}

.form-item {
  margin-right: 10px;
}
.my-custom-container {
  display: flex;
  align-items: center;
  height: 45px;
  background-color: white;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.my-custom-container div:first-child {
  margin-right: auto;
}

.my-custom-container span {
  font-weight: bold;
  margin-right: 10px;
}

.my-custom-container span:first-child {
  margin-left: 0;
}

.my-custom-container .el-select {
  flex: 1;
  margin-left: 10px;
}

.my-custom-container .el-option  {
  padding: 20px;
}
.el-tooltip {
  margin-right: 10px;
}

/* 路由的简单过渡动画效果 */
.v-enter {
  opacity: 0;
}
.v-enter-to {
  opacity: 1;
}
.v-enter-active {
  transition: 0.3s;
}
.v-leave {
  opacity: 1;
}
.v-leave-to {
  opacity: 0;
}
.v-leave-active {
  transition: 0.3s;
}
</style>
